<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>批量生成合同</title>
    <jsp:include page="../../import.jsp" flush="true"/>
    <script src="<%=path %>/resource/lib/plugins/ajaxfileupload.js"></script>
    <style>
        .project-span {
            border-radius: .25em;
            padding: .2em .6em .3em;
        }

        .project-span-success {
            color: #FFFFFF;
            background-color: #449d44;
            border-color: #449d44;
        }

        .project-span-dangeer {
            color: #FFFFFF;
            background-color: #d9534f;
            border-color: #d9534f;
        }

        .project-span-warning {
            color: #FFFFFF;
            background-color: #f0ad4e;
            border-color: #f0ad4e;
        }
    </style>
</head>
<body class="iframeBody">
<div class="Wrapper">
    <div class="searchArea">
        <form id="searchBar">
            <div class="fieldset1 clearFix">
                <div class="clearFix"></div>
                <div class="fieldBox" id="searchCstNmId">
                    <div class="label">请填写要生成的合同模板id(逗号分隔):</div>
                    <div class="field">
                        <input name="templateId" id="templateId" type="text" placeholder="为空则生成所有，不知道模板id联系开发">
                    </div>
                </div>
                <div class="fieldBox" id="searchCstNmId">
                    <div class="label">选择合同:</div>
                    <div class="field">
                        <input name="excelFile" id="excelFile" type="file">
                    </div>
                </div>
                <div class="btnsBox formBtns notRight">
                    <span onclick="window.open('http://sucai.file.alimmdn.com/temp/batchMakeContTemp.xls?1')" class="sq-button-round">下载导入模板</span>
                </div>
                <div class="btnsBox formBtns notRight">
                    <span onclick="importExcel();" class="sq-button-round">导入</span>
                </div>
                <%--		<div class="btnsBox formBtns notRight">
                            <span  onclick="makeCont();"  class="sq-button-round">生成合同(同步)</span>
                        </div>--%>
                <div class="btnsBox formBtns notRight">
                    <span onclick="makeContAjax();" class="sq-button-round">生成合同</span>
                </div>


            </div>
        </form>
    </div>
</div>
<div id="batchMakeGrid" class="sq-grid"></div>
</div>

<script type="text/javascript">

    var batchNumber = "";
    var forcedSignature = [{forcedSignature: 1, text: '是'}, {forcedSignature: 0, text: '否'}];
    var cfgRender = [];
    var dateJson = {"Rows": []};
    var grid = null;

    //初始化表单
    function initForm() {
        $("#searchBar").ligerForm();
    }

    $(function () {
        initGrid();
        if (localStorage.getItem("batchAddContBatchNumber")) {
            loadDataByBatchNumber(localStorage.getItem("batchAddContBatchNumber"));
        }
    });

    /**
     * 加载表格数据
     * @param batchNumber
     */
    function loadDataByBatchNumber(bn) {
        localStorage.setItem("batchAddContBatchNumber", bn);
        batchNumber = bn;
        var upload_dialog = UIUtils.alertWaiting("加载数据中...", function () {
        });
        $.post("<%=path%>/project/prjContCreatRec/selectListByBatchNumber.do", {batchNumber: bn}, function (resp) {
            dateJson.Rows = JSON.parse(resp).data;
            grid.set({data: dateJson});
            upload_dialog.close();
        });
    }

    //初始化列表
    function initGrid() {
        $("#batchMakeGrid").ligerGrid({
            columns: [
                { display: '批次', name: 'batchNo', width: 150},
                {display: '合同号', name: 'lsCntNo', minWidth: 140},
                {display: '提示信息', name: 'desc', minWidth: 140, render: errorInfoRender},
                {display: '客户', name: 'cstNm', minWidth: 60, align: 'center', enabledSort: true},
                {display: '客户经理', name: 'cstMgrNm', minWidth: 60, align: 'center', enabledSort: true},
                /*  { display: '项目类型', name: 'prjTypCdNm', width: 150, enabledSort:true},*/
                {display: '项目名称', name: 'prjNm', minWidth: 60, enabledSort: true},
                {
                    display: '项目配置',
                    name: 'cfgCd',
                    minWidth: 60,
                    enabledSort: true,
                    editor: {type: 'select', data: cfgRender, valueField: 'value', textField: 'title'}
                },
                {
                    display: '是否强签', name: 'forceSign', minWidth: 60, enabledSort: true, render: function (item) {
                        if (parseInt(item.forceSign) == 1) {
                            return '是';
                        } else {
                            return '否';
                        }

                    }, editor: {type: 'select', data: forcedSignature, valueField: 'forcedSignature', textField: 'text'}
                }, getGridOperColumnContent()

            ],
            data: dateJson,
            usePager: false,
            sortName: 'contractNo',
            width: '100%',
            height: '99%',
            checkbox: false,
            rownumbers:true,
            enabledEdit: true,
            onAfterEdit: f_onAfterEdit,
            onBeforeEdit: f_onBeforeEdit,
        });
        grid = liger.get("batchMakeGrid");
    }


    //Grid操作列

    function f_onAfterEdit(e) {
        $.post('<%=path%>/project/prjContCreatRec/modify.do', {
            id: e.record.id,
            forceSign: e.record.forceSign,
            cfgCd: e.record.cfgCd
        }, function (data) {
            grid.endEdit(e.rowindex);
        })
    }

    function f_onBeforeEdit(e) {
        /**
         * 动态渲染合同配置
         */
        if (e.column.columnname == "cfgCd") {
            e.column.editor.data = e.record.listCfgCd;
        }

    }

    //导入
    function importExcel() {

        if ($("#excelFile").val().length == 0) {
            alert("请选择要上传的文件!");
        } else {
            var upload_dialog = UIUtils.alertWaiting("上传中...", function () {
            });
            $.ajaxFileUpload
            (
                {
                    url: '<%=path%>/project/prjContCreatRec/addBatchByUpload.do', //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议，一般设置为false
                    fileElementId: 'excelFile', //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        upload_dialog.close();
                        if (data.success == 1) {
                            batchNumber = data.data;
                            loadDataByBatchNumber(data.data);
                        } else {
                            alert(data.info);
                        }


                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        upload_dialog.close();
                        console.log(data)
                    }
                })
        }
    }


    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
        }
        return dateStr;
    }


    function iframeResize() {
        if (parent.mainApp) {
            parent.mainApp.parentTab.onResize();
        }
        ;
    }

    function errorInfoRender(rowdata, index, value) {
        var dataState = rowdata.isValid;
        var cfgCd = rowdata.cfgCd;
        var status = rowdata.status;
        if (dataState == 1) {
            if (cfgCd == '' || cfgCd == null) {
                return "<span class='project-span project-span-dangeer'>请先选择合同配置</span>";
            } else {
                if(status==1){
                    return "<span class='project-span project-span-success'>" + value + "</span>";
                }else {

                    return "<span class='project-span project-span-warning'>" + value + "</span>";

                }

            }
        } else {

            return "<span class='project-span project-span-dangeer'>" + value + "</span>";

        }
    }

    //用来当做合同结束生成的标识
    var countExc = 0;

    /**
     * 生成合同
     */
    function makeContAjax() {
        if (countExc == 0) {
            countExc=1;
            $.ligerDialog.confirm('是否生成合同', function (yes) {
                if(yes){
                    var data = grid.getData();
                   ajaxAddCont(data, 0);
                }else{
                    countExc=0;
                }
            });
        } else {
            alert("生成中不要重复点击")
        }


    }

    function ajaxAddCont(data, i) {
        $.ligerDialog.closeWaitting();
       var  id=data[i].id;
        $.ligerDialog.waitting('生成第'+(i+1)+'个合同【'+data[i].lsCntNo+'】中,请稍候...');
        $.post('<%=path%>/project/prjContCreatRec/addContractByLogId.do', {logId: id,templateId:$("#templateId").val()}, function (resp) {
            $.ligerDialog.closeWaitting();
            if (i>=(data.length-1)) {
                loadDataByBatchNumber(batchNumber);
                countExc = 0;
            }else{
                ajaxAddCont(data,++i);
            }

        });
    }

    //同步生成合同
    function makeCont() {
        var cont = 0;
        var data = grid.getData();
        $(data).each(function (i, o) {
            if (o.cfgCd == '' || o.cfgCd == null) {
                cont++;
                return;
            } else {

            }
        })
        if (cont > 0) {
            alert("请配置项目配置");
        } else {
            makeContByBatchNumber(batchNumber);
        }


    }

    function makeContByBatchNumber(batchNumber) {

        var upload_dialog = UIUtils.alertWaiting("生成合同中...", function () {
        });
        $.post('<%=path%>/project/prjContCreatRec/addContByBatchNumber.do', {batchNumber: batchNumber}, function (data) {
            var resp = JSON.parse(data);
            if (resp.success == 1) {
                loadDataByBatchNumber(batchNumber);
            } else {
                upload_dialog.close();
                alert(resp.info)
                // loadDataByBatchNumber(batchNumber);
            }
            upload_dialog.close();

        })
    }

    //Grid操作列
    function getGridOperColumnContent() {
        var data = {
            display: '操作',
            isSort: false,
            width: 100,
            render: function (rowdata, rowindex, value) {
                var h = '<a class="sq-button-hasicon" href="javascript:repeatMake(\'' + rowdata.id + '\',\'' + rowdata.cfgCd + '\')">生成合同</a>';

                return h;
            }
        }
        return data;
    }

    function repeatMake(id, cfgCd) {
        if (cfgCd == '' || cfgCd == null || cfgCd == 'null') {
            alert("请配置项目配置");
        } else {
            var upload_dialog = UIUtils.alertWaiting("生成合同中...", function () {
            });
            $.post('<%=path%>/project/prjContCreatRec/addContractByLogId.do', {logId: id,templateId:$("#templateId").val()}, function (data) {
                var resp = JSON.parse(data);
                if (resp.success == 1) {
                    loadDataByBatchNumber(batchNumber);
                } else {
                    upload_dialog.close();
                    alert(resp.info)
                    // loadDataByBatchNumber(batchNumber);
                }
                upload_dialog.close();

            })
        }
    }
</script>

</body>
</html>